package com.yorick.resource.controller;

import com.yorick.common.util.YorickUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * @program: vr_manage
 * @description: 文件上传
 * @author: 陈治杰
 * @create: 2021-08-09 10:38
 **/
@Controller
@RequestMapping("resource")
public class FileUploaderController {
    public static final String BASE_PATH="/usr/local/apache-tomcat-8.5.89/webapps/resources/";//测试路径

    @RequestMapping(value = "uploadFile",method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String uploadFile(@RequestParam("logFile") MultipartFile uploadFile, HttpSession session){
        String filename = uploadFile.getOriginalFilename();
        filename=System.currentTimeMillis()+"&"+filename;
        try {
            File file = new File(BASE_PATH,filename);
            uploadFile.transferTo(file);
            if(filename.split("\\.").length>1){
                String filetype = filename.split("\\.")[1];
                if(filetype.equals("zip")){
                    String zipDir=BASE_PATH+filename.split("&")[0]+"/";
                    File fold=new File(zipDir);
                    if(!fold.exists()){//如果文件夹不存在
                        fold.mkdir();//创建文件夹
                    }
                    YorickUtil.decompressZip(BASE_PATH+filename,zipDir);
                }else if(filetype.equals("jpg")||filetype.equals("jpeg")||filetype.equals("png")){
                    Thumbnails.of(BASE_PATH+filename)
                            .scale(1f)
                            .outputQuality(0.5f)
                            .toFile(BASE_PATH+filename);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return filename;
    }
}

